<template>
  <image class="forbiden-page" src="../../static/img/msg/nopower.png" v-if="isForbiden"></image>

  <view class="content" v-else>
    <view class="navigation"></view>
    <view class="settings">
      <uni-icons @click="openSetting" type="settings-filled" size="25" color="#333"></uni-icons>
      <view>
        <!-- #ifdef APP-PLUS -->
        <uni-icons style="margin-right: 20rpx" @click="scanQrcode" type="scan" size="25" color="#333"></uni-icons>
        <!-- #endif -->
        <uni-icons v-if="!batch_processing" type="tune" size="25" color="#333" @click="startSelectComputer"></uni-icons>
        <uni-icons v-else type="tune-filled" size="25" color="#333" @click="startSelectComputer"></uni-icons>
      </view>
    </view>
    <view class="computer-list">
      <view :class="batchProcessingArray.includes(computer) ? (failedList.includes(computer) ? 'computer-item-fail' : 'computer-item-success') : 'computer-item'" @click="computerClickHandler(computer)" v-for="computer in computerList" :key="computer.ip">
        <view class="left">
          <uni-icons v-if="computer.status && computer.status === '查询中'" type="spinner-cycle" size="45" color="#aaa"></uni-icons>
          <uni-icons v-else-if="computer.status && computer.status === '在线'" type="checkbox" size="45" color="#42b983"></uni-icons>
          <uni-icons v-else type="info" size="45" color="#dd524d"></uni-icons>
        </view>
        <view class="right">
          <view class="computer-status">{{ computer.status ? computer.status : "连接中..." }}</view>
          <view class="computer-name">{{ computer.name }}</view>
          <view class="computer-address">{{ computer.port ? computer.ip + ":" + computer.port : computer.ip }}</view>
        </view>
      </view>
      <view class="add-computer" @click="open" v-if="!batch_processing">
        <view class="left">
          <uni-icons type="plus" size="45" color="#aaa"></uni-icons>
        </view>
        <view class="right">
          <view class="add-computer-name">添加设备</view>
        </view>
      </view>
    </view>

    <!-- 设备信息添加表单组件 -->
    <computer-form ref="computerPopup"></computer-form>
    <!-- 设置抽屉组件 -->
    <Settings ref="SettingsRef" />
    <!-- 顶部消息通知组件 -->
    <top-notification ref="topNotificationRef" />
    <!-- 批量操作抽屉组件（右侧） -->
    <batch-processing ref="batchProcessingRef" :batchProcessingArray="batchProcessingArray" @closeEvent="isBatchProcessing = false" @failedEvent="failedEvent" />
    <!-- 批量操作抽屉（底部） -->
    <view class="batch-processing-box fadeUpAnimation" :class="batchProcessingArray.length !== 0 ? 'fadeUp' : ''" v-if="batchProcessingArray.length !== 0 && !isBatchProcessing">
      <view class="icon"></view>
      <view class="btn-group">
        <button class="base-button btn" @click="exportConfiguration">批量导出</button>
        <button class="base-button btn danger-button" @click="deleteConfiguration">批量删除</button>
        <button class="base-button btn" @click="openBatchProcessing">批量操作</button>
      </view>
    </view>
    <!-- 密码设置提示 -->
    <tip-popup ref="pwdTipRef" content="暂未设置密码，建议请先前往【安全配置】设置密码，并开启【密码验证】" confirmText="立即设置" tip-id="pwd" @confirmEvent="setPassword"></tip-popup>
  </view>
</template>

<script setup>
import { getComputerInfo } from "@/api/control.js";
import { ref, onMounted, watch } from "vue";
import { onPullDownRefresh } from "@dcloudio/uni-app";
import { storeToRefs } from "pinia";
import useComputerStore from "@/store/modules/computer.js";
import useSafeStore from "@/store/modules/safe.js";
import { areArraysEqual } from "@/utils/tools.js";
import { isAuthPass } from "../../utils/authentication";

import Settings from "@/pages/index/components/settings";
import batchProcessing from "@/pages/index/components/batchProcessing";
import _ from "lodash";

import { useRouterCheck } from "@/composables/index.js";
// 路由判断函数(解构赋值为路由判断结果)
useRouterCheck();

let failedList = ref([]);

const failedEvent = ($event) => {
  failedList.value = $event;
};

// safe.js pinia
const safeStore = useSafeStore();

let isForbiden = ref(true);

watch(
  () => safeStore.isAuth,
  (newV) => {
    if (safeStore.fingerPrint || safeStore.usePassword) {
      if (!newV) {
        isForbiden.value = true;
      } else {
        isForbiden.value = false;
        scanComputer();
      }
    } else {
      isForbiden.value = false;
    }
  },
  { immediate: true }
);

// 设置密码提示弹窗组件实例
const pwdTipRef = ref();
// 打开弹窗
const pwdTipOpen = () => {
  if (!safeStore.password) pwdTipRef.value.open();
};

const setPassword = () => {
  uni.navigateTo({
    url: "/pages/security/index",
  });
};

// 扫描二维码
const scanQrcode = () => {
  if (isAuthPass()) return;
  uni.scanCode({
    autoZoom: true,

    success: async function (res) {
      let errorTip = (message) => {
        topNotificationRef.value.sendPopupTip({
          type: "error",
          message,
          duration: 1000,
        });
      };
      let data = JSON.parse(res.result);
      // 判断外层是不是对象
      if (Object.prototype.toString.call(data) !== "[object Object]") return errorTip("二维码内容错误");
      if (!areArraysEqual(Object.keys(data), ["name", "ip", "port", "key", "custom_command"]) || !Array.isArray(data.custom_command)) return errorTip("二维码数据缺失");
      // 判断设配参数
      for (let i = 0; i < computerList.value.length; i++) {
        const item = computerList.value[i];
        if (item.ip === data.ip && item.port === data.port) return errorTip("设备已存在");
      }

      try {
        let res = await getComputerInfo(data);
        if (res.code === 200) {
          data.status = "在线";
        } else {
          data.status = "离线";
        }
      } catch (err) {
        data.status = "离线";
      }
      computerList.value.push(data);
      computerStore.updateComputerList(_.cloneDeep(computerList.value));
      topNotificationRef.value.sendPopupTip({
        type: "success",
        message: "设备导入成功",
        duration: 1000,
      });
    },
    fail: (res) => {
      topNotificationRef.value.sendPopupTip({
        type: "error",
        message: "请在设置中允许摄像头权限",
        duration: 1000,
      });
    },
  });
};

//设置组件实例
const SettingsRef = ref();

const openSetting = () => {
  SettingsRef.value.open();
};

// 判断主句是否开机
onMounted(() => {
  pwdTipOpen();
  if (!(safeStore.fingerPrint || safeStore.usePassword)) scanComputer();
});

onPullDownRefresh(() => {
  scanComputer(true);
});

const computerStore = useComputerStore();
const { computerList } = storeToRefs(computerStore);

// 扫描所有设备判断是否在线
const scanComputer = async (stoploading) => {
  for (let i = 0; i < computerList.value.length; i++) {
    let item = computerList.value[i];
    item.status = "查询中";
    let res = await getComputerInfo(item);
    if (res.code === 200) {
      item.status = "在线";
    } else {
      item.status = "离线";
    }
  }
  computerStore.updateComputerList(computerList.value);
  if (stoploading) uni.stopPullDownRefresh();
};

// 获取弹窗表单实例
const computerPopup = ref();

const open = () => {
  computerPopup.value.openAddComputer();
};

const close = () => {
  computerPopup.value.closeAddComputer();
};

//跳转设备详情页
const goDetail = (computer) => {
  uni.navigateTo({
    url: `/pages/detail/index?ip=${computer.ip}&port=${computer.port}`,
  });
};

let batch_processing = ref(false);

// 开启批量设置
const startSelectComputer = () => {
  batch_processing.value = !batch_processing.value;
  if (batch_processing.value) {
    topNotificationRef.value.sendPopupTip({
      type: "success",
      message: "批量处理开启",
      duration: 1000,
    });
  } else {
    batchProcessingArray.value = [];
    topNotificationRef.value.sendPopupTip({
      type: "info",
      message: "批量处理关闭",
      duration: 1000,
    });
  }
};

// 顶部提示横幅实例
const topNotificationRef = ref();

// 批处理设备数组
let batchProcessingArray = ref([]);

// 设备点击事件
const computerClickHandler = (computer) => {
  if (batch_processing.value) {
    let inArray = batchProcessingArray.value.indexOf(computer);
    if (inArray === -1) {
      batchProcessingArray.value.push(computer);
    } else {
      batchProcessingArray.value.splice(inArray, 1);
    }
    let inFailArray = failedList.value.indexOf(computer);
    if (inFailArray !== -1) {
      failedList.value.splice(inFailArray, 1);
    }
  } else {
    goDetail(computer);
  }
};

// 批量导出配置信息
const exportConfiguration = () => {
  if (isAuthPass()) return;
  let formatBatchProcessingArray = _.cloneDeep(batchProcessingArray.value);
  formatBatchProcessingArray.map((item) => delete item.status);
  uni.setClipboardData({
    data: JSON.stringify(formatBatchProcessingArray),
    success: () => {
      topNotificationRef.value.sendPopupTip({
        type: "success",
        message: "导出成功，已复制至粘贴板！",
      });
    },
    fail: () => {
      topNotificationRef.value.sendPopupTip({
        type: "error",
        message: "导出失败，请检查应用粘贴权限是否给予",
      });
    },
  });
};

// 批量删除配置
const deleteConfiguration = () => {
  if (isAuthPass()) return;
  let filterComputerListArray = computerList.value.filter((item) => {
    if (!batchProcessingArray.value.includes(item)) {
      return item;
    }
  });
  computerStore.updateComputerList(filterComputerListArray);
};

// 更多批量操作列表
const batchProcessingRef = ref();

// 是否更多批量操作
let isBatchProcessing = ref(false);

const openBatchProcessing = () => {
  isBatchProcessing.value = true;
  batchProcessingRef.value.open();
};
</script>

<style lang="scss" scoped>
.forbiden-page {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -80%);
  height: 512rpx;
  width: 512rpx;
}
.content {
  .navigation {
    height: var(--status-bar-height);
  }
  .settings {
    box-sizing: border-box;
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
  }
  .computer-list {
    width: 100vw;
    display: flex;
    flex-wrap: wrap;
    box-sizing: border-box;
    padding: 20rpx;
    gap: 20rpx;
    .computer-item {
      width: 343rpx;
      display: flex;
      background-color: rgba(255, 255, 255, 0.8);
      justify-content: space-between;
      border: 2rpx solid rgba(0, 0, 0, 0.1);
      border-radius: 8px;
      box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(0, 0, 0, 0.1);
      align-items: center;
      box-sizing: border-box;
      padding: 10px 0;
      .left {
        width: 35%;
        text-align: center;
      }
      .right {
        width: 65%;
        .computer-status {
          font-size: 20px;
          font-weight: bold;
          color: #333;
        }
        .computer-name {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 12px;
          color: #4f4f4f;
        }
        .computer-address {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          font-size: 10px;
          color: #aaa;
        }
      }
    }
    .computer-item-success {
      @extend .computer-item;
      border: 4rpx solid #2979ff;
      box-shadow: 10rpx 10rpx 20rpx 0rpx rgba(41, 121, 255, 0.2);
    }
    .computer-item-fail {
      @extend .computer-item;
      border: 4rpx solid $uni-color-error;
      box-shadow: 10rpx 10rpx 20rpx 0rpx rgb(221, 82, 77, 0.2);
    }
    .add-computer {
      @extend .computer-item;
      height: 78px;
      .add-computer-name {
        font-size: 17px;
        font-weight: bold;
        color: #aaa;
      }
    }
  }
  .popup {
    width: 600rpx;
    background-color: #ffffff;
    border-radius: 10rpx;
    box-sizing: border-box;
    padding: 20rpx;
    .head {
      display: flex;
      justify-content: space-between;
      align-items: center;

      text {
        font-size: 35rpx;
        font-weight: bold;
        color: #333;
      }
    }
    .body {
      margin-top: 20px;
    }
  }
  .batch-processing-box {
    width: 100%;
    height: 80px;
    position: fixed;
    bottom: 0px;
    left: 0px;
    transform: translateX(-50%);
    box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0, 0, 0, 0.15);
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 20rpx 20rpx 0 0;
    padding: 0 10rpx 0 10rpx;
    padding-bottom: env(safe-area-inset-bottom);
    box-sizing: border-box;
    transform: translate(80px);

    .icon {
      margin-top: 5px;
      height: 5px;
      width: 100rpx;
      background-color: #4f4f4f75;
      border-radius: 10px;
    }
    .btn-group {
      margin-top: 10px;
      display: flex;
      width: 100%;
      justify-content: space-around;
    }
    .btn {
      width: 230rpx;
    }
  }
}
</style>
